package cn.edu.swu.bc.utils;

import cn.edu.swu.bc.entity.Blog;
import cn.edu.swu.bc.filter.AuthFilter;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    public static List<String> getBlogContent(int blogId, HttpServletRequest request) throws IOException {
        List<String> blogContent=new ArrayList<>();
        //通过request找到项目真实路径，找到博客文件并读取
        String blogsPath = request.getServletContext().getRealPath("./") +File.separator+"blogs"+ File.separator+blogId+".txt";
        File file=new File(blogsPath);
        FileReader fd=new FileReader(file, Charset.forName("UTF-8"));
        BufferedReader reader=new BufferedReader(fd);
        String tmpstring;
        while ((tmpstring= reader.readLine())!=null)
        {
            blogContent.add(tmpstring);
        }
        fd.close();
        reader.close();

        return  blogContent;
    }

    public static void deleteBlogPic(int blogId, HttpServletRequest request){
        String pics=null;
        try {
            Blog blog= DBUtils.getBlogInfoByID(blogId);
            pics=blog.getPic();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(pics!=null)
        {
            String [] picsName= pics.split(",");
        //通过request找到项目真实路径，找到博客文件并读取
        for (String name:picsName
             ) {
            String blogsPath = request.getServletContext().getRealPath("./") +File.separator+"blogsPic"+ File.separator+name;
            File file=new File(blogsPath);
            //删除博客文章
            file.delete();
            System.out.println(name);
        }}
    }
    public static void deleteBlogContent(int blogId, HttpServletRequest request) throws IOException {
        List<String> blogContent=new ArrayList<>();
        //通过request找到项目真实路径，找到博客文件并读取
        String blogsPath = request.getServletContext().getRealPath("./") +File.separator+"blogs"+ File.separator+blogId+".txt";
        File file=new File(blogsPath);
        //删除博客文章
        file.delete();
    }
}
